<template>
    <el-form ref="subjectEditForm" style="max-width: 100%;" :model="editForm" :rules="rules" label-width="auto">
        <el-form-item label="学科" prop="name" required>
            <el-input v-model="editForm.name" />
        </el-form-item>
        <el-form-item label="年级" required>
            <el-select v-model="editForm.level" placeholder="年级">
                <el-option v-for="level in level.list" :key="level.value" :label="level.name" :value="level.value" />
            </el-select>
        </el-form-item>
        <el-form-item>
            <el-button type="primary" @click="submitForm(subjectEditForm)">
                提交
            </el-button>
            <el-button @click="resetForm(subjectEditForm)">重置</el-button>
        </el-form-item>
    </el-form>
</template>

<script setup lang="ts">
import { subjectEdit, subjectSelect } from '@/api/education';
import router from '@/router';
import { useLevelStore } from '@/store/level';
import { type FormInstance, type FormRules } from 'element-plus';
import { reactive, ref } from 'vue';
import { useRouter } from 'vue-router';

const { currentRoute } = useRouter()
const subjectId = ref<number>()
if (currentRoute.value.query.id) {
    subjectId.value = Number(currentRoute.value.query.id as string)
    // console.log(subjectId.value);
    getData()
}
const level = useLevelStore()
export interface RuleForm {
    id: any
    name: string
    level?: number | string
    levelName: string
}
const editForm = reactive<RuleForm>({
    id: subjectId.value,
    name: '',
    level: '',
    levelName: ''
})
const subjectEditForm = ref<FormInstance>()
const rules = reactive<FormRules<RuleForm>>({
    name: [
        { required: true, message: '请输入学科', trigger: 'blur' },
    ],
    level: [
        {
            required: true,
            message: '请选择年级',
            trigger: 'change',
        },
    ],
})
function getData() {
    subjectSelect(subjectId.value).then(res => {
        // console.log(res.response);
        editForm.name = res.response?.name as string
        editForm.level = res.response?.level
    })
}
function handleEdit() {
    editForm.levelName = (level.list.find(item => item.value == editForm.level)?.name) as string
    subjectEdit(editForm).then(res => {
        // console.log(res.response);
        if (res.code == 1) {
            router.push('/subject')
        }
    })
}
const submitForm = async (formEl: FormInstance | undefined) => {
    if (!formEl) return
    await formEl.validate((valid, fields) => {
        if (valid) {
            handleEdit()
        } else {
            console.log('error submit!', fields)
        }
    })
}
const resetForm = (formEl: FormInstance | undefined) => {
    if (!formEl) return
    formEl.resetFields()
}
</script>